package com.example.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.api.ResultCode;
import com.example.common.api.ResultUtil;
import com.example.user.mapper.RoleMapper;
import com.example.user.model.dto.RoleDTO;
import com.example.user.model.po.RolePO;
import com.example.user.model.po.UserRoleRulePO;
import com.example.user.model.vo.RoleVO;
import com.example.user.service.IRoleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RoleService extends ServiceImpl<RoleMapper, RolePO> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public ResultUtil createRole(RoleVO roleVO) {
        log.info("create role begin, receive params: {}", roleVO.toString());

        RolePO rolePO = new RolePO();
        BeanUtils.copyProperties(roleVO, rolePO);

        //默认开启
        rolePO.setDeleted(0);
        int row = roleMapper.insert(rolePO);

        if (row > 1){
            RoleDTO roleDTO = new RoleDTO();
            BeanUtils.copyProperties(rolePO, roleDTO);

            log.info("create role success, role name {}, role code {}", roleDTO.getRoleName(), roleDTO.getRoleCode());

            return ResultUtil.success(roleDTO);
        }

        log.error("create role fail, role name {}", rolePO.getRoleName());
        return ResultUtil.failed(ResultCode.CREATE_ROLE_ERROR);
    }

    @Override
    public ResultUtil updateRoleStatus(Long roleId, int status) {
        log.info("set role status begin, receive params: id: {}, status: {}", roleId, status);

        if (status == 1){
            List<UserRoleRulePO> list = roleMapper.getUserRoleRule(null, roleId);
            if (!list.isEmpty()){
                log.info("查询角色下的用户: {}", list.toString());
                return ResultUtil.failed(ResultCode.DISABLE_ROLE_ERROR);
            }
        }

        RolePO rolePO = new RolePO();
        rolePO.setId(roleId);
        rolePO.setDeleted(status);
        int row = roleMapper.updateById(rolePO);

        if (row > 0){
            log.info("modify role status success, role id: {}, role status: {}", roleId, status);
            Map<String, Boolean> map = new HashMap<>();
            map.put("result", true);
            return ResultUtil.success(map);
        }

        log.error("set role status fail, id: {}, status: {}", roleId, status);
        return ResultUtil.failed(ResultCode.UPDATE_ROLE_STATUS_ERROR);
    }

}
